<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
    >
      <el-form-item :label="$t('employer')" prop="employerId">
        <employerSelect
          v-model="queryParams.employerId"
          @change="employerChange"
        ></employerSelect>
      </el-form-item>
      <el-form-item
        :label="$t('department')"
        prop="employerDeptId"
        v-show="queryParams.employerId"
      >
        <treeselect
          :normalizer="normalizer"
          v-model="queryParams.employerDeptId"
          :options="deptOptions"
          :show-count="true"
          :placeholder="$t('please_select', { name: $t('department') })"
          style="width: 240px; height: 32px"
        />
      </el-form-item>
      <el-form-item :label="$t('employee_name')" prop="employeeName">
        <el-input
          v-model="queryParams.employeeName"
          :placeholder="$t('please_enter', { name: $t('employee_name') })"
          :show-word-limit="true"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >{{ $t("search") }}</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">{{
          $t("reset")
        }}</el-button>
      </el-form-item>
    </el-form>
    <template v-if="queryParams.employerId">
      <div class="option-block" v-if="editStatus == 1">
        <div class="option-line">
          <div class="line-label">{{ $t("shift") }}：</div>
          <div class="line-value">
            <el-checkbox-group
              v-model="checkClasses"
              :max="1"
              @change="classesChange"
            >
              <el-checkbox
                :label="item.id"
                v-for="(item, index) in classesList"
                :key="index"
                style="margin-bottom: 10px"
                >{{ item.shiftName }}</el-checkbox
              >
            </el-checkbox-group>
          </div>
        </div>
        <div class="option-line">
          <div class="line-label">{{ $t("cycle_shift") }}：</div>
          <div class="line-value">
            <el-checkbox-group
              v-model="checkCycle"
              :max="1"
              @change="cycleChange"
            >
              <el-checkbox
                :label="item.id"
                v-for="(item, index) in cycleList"
                :key="index"
                style="margin-bottom: 10px"
                >{{ item.cycleName }}</el-checkbox
              >
            </el-checkbox-group>
          </div>
        </div>
      </div>

      <div class="option-block" v-else>
        <div class="option-line">
          <div class="line-label">{{ $t("shift") }}：</div>
          <div class="line-value">
            <el-radio-group
              v-model="queryParams.shiftId"
              size="mini"
              @change="getList"
            >
              <el-radio class="radio-class" :label="null" border>{{
                $t("all")
              }}</el-radio>
              <el-radio
                class="radio-class"
                :label="item.id"
                v-for="(item, index) in classesList"
                :key="index"
                border
                >{{ item.shiftName }}</el-radio
              >
            </el-radio-group>
          </div>
        </div>
        <div class="option-line">
          <div class="line-label">{{ $t("cycle_shift") }}：</div>
          <div class="line-value">
            <el-radio-group
              v-model="queryParams.cycleId"
              size="mini"
              @change="getList"
            >
              <el-radio class="radio-class" :label="null" border>{{
                $t("all")
              }}</el-radio>
              <el-radio
                class="radio-class"
                :label="item.id"
                v-for="(item, index) in cycleList"
                :key="index"
                border
                >{{ item.cycleName }}</el-radio
              >
            </el-radio-group>
          </div>
        </div>
        <div class="option-line" style="align-items: center">
          <div class="line-label">{{ $t("status") }}：</div>
          <div class="line-value">
            <el-radio-group
              v-model="queryParams.status"
              size="mini"
              @change="getList"
            >
              <el-radio class="radio-class" border :label="null">{{
                $t("all")
              }}</el-radio>
              <el-radio class="radio-class" border label="1">{{
                $t("published")
              }}</el-radio>
              <el-radio class="radio-class" border label="0">{{
                $t("unpublished")
              }}</el-radio>
            </el-radio-group>
          </div>
        </div>
      </div>

      <el-row
        :gutter="20"
        type="flex"
        align="middle"
        justify="space-between"
        class="mb8"
      >
        <el-col :span="1.5">
          <el-select
            v-model="currentYear"
            @change="selectYear"
            style="width: 100px"
          >
            <el-option
              :label="item.label"
              :value="item.value"
              v-for="(item, index) in yearArr"
              :key="index"
            ></el-option>
          </el-select>
        </el-col>
        <el-col :span="1" v-for="(item, index) in 12" :key="index">
          <div
            class="month-text"
            :class="{ active: currentMonth == index }"
            @click="selectMonth(index + 1)"
          >
            {{ index + 1 }}{{ $t("month") }}
          </div>
        </el-col>
        <el-col :span="1.5">
          <el-button-group>
            <el-button icon="el-icon-arrow-left" @click="lastWeek">{{
              $t("last_week")
            }}</el-button>
            <el-button @click="setDate(new Date())">{{
              $t("this_week")
            }}</el-button>
            <el-button @click="nextWeek">
              {{ $t("next_week") }}
              <i class="el-icon-arrow-right el-icon--right"></i>
            </el-button>
          </el-button-group>
        </el-col>
      </el-row>

      <el-table
        v-loading="loading"
        :data="dataList"
        border
        style="width: 100%; color: black"
        ref="mainTable"
        :cell-style="cellStyle"
        :header-cell-style="headerCellStyle"
        @header-click="handleHeaderClick"
        @cell-click="handleCellClick"
        :max-height="tableHeight"
      >
        <el-table-column
          prop="empName"
          :label="$t('employee_name')"
          align="center"
          width="120"
          :colIndex="0"
        />
        <el-table-column
          align="center"
          v-for="(item, index) in dateArr"
          :key="index + item"
          :label="formatDate(new Date(item), 'm/d', true)"
          :render-header="todayDate == item ? renderHeader : renderNot"
          :data-index="index + 1"
          className="class-cell"
        >
          <template slot-scope="scope">
            <div
              class="table-cell-item"
              v-for="(dayItem, dayIndex) in scope.row.dayList"
              :key="dayIndex"
            >
              <div v-if="dayItem.date == item">
                <div v-if="dayItem.classesList && dayItem.classesList.length">
                  <div class="status-block">
                    <i class="el-icon-finished"></i>
                    <!-- <i
                      class="el-icon-delete"
                      @click="deleteIndexClass(scope.row, dayIndex)"
                      v-if="editStatus && dayItem.isEdit"
                    ></i> -->
                    <i
                      class="el-icon-delete"
                      @click="deleteIndexClass(scope.row, dayIndex)"
                      v-if="editStatus"
                    ></i>
                  </div>
                  <div
                    class="tag-item"
                    :style="{
                      background: classItem.shiftColor,
                      color: '#fff',
                    }"
                    v-for="(classItem, classIndex) in dayItem.classesList"
                    :key="classIndex"
                  >
                    {{ classItem.shiftName }}
                  </div>
                </div>
                <template v-if="dayItem.customHolidayNames.length">
                  <div
                    class="tag-item"
                    style="background: #f8b501; color: #fff"
                    v-for="(
                      holiday, holidayIndex
                    ) in dayItem.customHolidayNames"
                    :key="holidayIndex"
                  >
                    {{ holiday }}
                  </div>
                </template>
              </div>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <el-row
        :gutter="20"
        type="flex"
        align="middle"
        justify="end"
        style="margin-top: 20px"
      >
        <el-button type="primary" plain @click="batchOption">{{
          $t("batch_scheduling")
        }}</el-button>

        <template v-if="editStatus">
          <el-button type="info" plain @click="editOption(false)">{{
            $t("cancel_editing")
          }}</el-button>
          <el-button type="warning" plain @click="saveOption">{{
            $t("save")
          }}</el-button>
        </template>
        <el-button type="success" plain @click="editOption(true)" v-else>{{
          $t("edit_schedule")
        }}</el-button>
        <el-button type="primary" @click="postOption">{{
          $t("publish")
        }}</el-button>
      </el-row>
    </template>
    <template v-else>
      <el-empty :description="$t('employer_yet')" class="empty">
        <div class="tip">{{ $t("selecting_scheduling_calendar") }}</div>
      </el-empty>
    </template>
    <!-- 添加或修改周期班对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item :label="$t('forms_of_scheduling')" prop="scheduleForm">
          <el-select
            v-model="form.scheduleForm"
            :placeholder="
              $t('please_select', { name: $t('forms_of_scheduling') })
            "
            @change="changeSchedulingForm"
          >
            <el-option :label="$t('shift_scheduling')" value="1"></el-option>
            <el-option :label="$t('periodic_scheduling')" value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          :label="$t('methods_of_scheduling')"
          prop="scheduleMethod"
        >
          <el-select
            v-model="form.scheduleMethod"
            :placeholder="
              $t('please_select', { name: $t('methods_of_scheduling') })
            "
            @change="changeMethod"
          >
            <el-option :label="$t('cycle_scheduling')" value="1"></el-option>
            <el-option :label="$t('monthly_scheduling')" value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          :label="$t('select_shift')"
          prop="classesId"
          v-if="form.scheduleForm == 1"
        >
          <el-checkbox-group v-model="form.classesId">
            <el-checkbox
              :label="item.id"
              v-for="(item, index) in classesList"
              :key="index"
              >{{ item.shiftName }}</el-checkbox
            >
          </el-checkbox-group>
        </el-form-item>
        <el-form-item
          :label="$t('select_cycle_shift')"
          prop="cycleId"
          v-if="form.scheduleForm == 0"
        >
          <el-radio-group v-model="form.cycleId">
            <el-radio
              class="radio-class"
              :label="item.id"
              v-for="(item, index) in cycleList"
              :key="index"
              >{{ item.cycleName }}</el-radio
            >
          </el-radio-group>
        </el-form-item>
        <el-form-item
          :label="$t('cycle_frequency')"
          v-show="form.scheduleMethod == 1"
        >
          <el-date-picker
            v-model="loopCycle"
            type="daterange"
            range-separator="-"
            :start-placeholder="$t('start_date')"
            :end-placeholder="$t('ending_date')"
            value-format="yyyy-MM-dd"
            :picker-options="pickerOptions"
            :append-to-body="false"
          ></el-date-picker>
        </el-form-item>

        <el-form-item
          :label="$t('cycle_frequency')"
          prop="cycleDateList"
          v-show="form.scheduleMethod == 0"
        >
          <el-date-picker
            ref="datesRef"
            type="dates"
            v-model="form.cycleDateList"
            :editable="false"
            value-format="yyyy-MM-dd"
            :placeholder="$t('please_select', { name: '' })"
            :append-to-body="false"
          ></el-date-picker>
        </el-form-item>
        <el-form-item
          :label="$t('weekly_scheduling')"
          prop="weeklyList"
          v-if="form.scheduleForm == 1 && form.scheduleMethod == 1"
        >
          <el-checkbox-group v-model="form.weeklyList">
            <el-checkbox
              :label="item.value"
              v-for="(item, index) in weeksList"
              :key="index"
              >{{ item.label }}</el-checkbox
            >
          </el-checkbox-group>
        </el-form-item>
        <el-form-item :label="$t('employee')">
          <el-button @click="checkTeamMember">{{ $t("select") }}</el-button>
          <div style="margin-top: 10px">
            <el-tag
              :key="index"
              v-for="(item, index) in checkTeamMemberList"
              closable
              :disable-transitions="false"
              @close="handleRemoveTeamMember(index)"
              style="margin-right: 10px"
              >{{ item.employeeName }}</el-tag
            >
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">{{
          $t("confirm")
        }}</el-button>
        <el-button @click="cancel">{{ $t("cancel") }}</el-button>
      </div>
    </el-dialog>

    <createdPeo
      ref="showTips"
      @handleChoosePeople="handleChoosePeople"
    ></createdPeo>
  </div>
</template>

<script>
import { listCycleAll } from "@/api/checkWork/cycle.js";
import { listClassesAll } from "@/api/checkWork/classes.js";
import {
  addBatchUpdate,
  getBatchList,
  updateClasses,
  postClasses,
} from "@/api/checkWork/calendar.js";
import { scheduleEmployeeList } from "@/api/custom/employeeList";
import { deptTree } from "@/api/custom/employerList";
import employerSelect from "@/views/components/custom/employerSelect.vue";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import createdPeo from "./createdPeo.vue";
export default {
  name: "calendar",
  components: {
    employerSelect,
    Treeselect,
    createdPeo,
  },
  data() {
    let _minTime = null;
    let _maxTime = null;
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 周期班表格数据
      cycleList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        employerId: null,
        employeeName: null,
      },
      deptOptions: [],
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        classesId: [
          {
            type: "array",
            required: true,
            message: this.$t("please_select", { name: this.$t("shift") }),
            trigger: "change",
          },
        ],
        cycleId: [
          {
            required: true,
            message: this.$t("cannot_empty", { name: this.$t("shift") }),
            trigger: "change",
          },
        ],
      },
      userList: [],

      dataList: [],
      dataListCopy: [],

      colIndex: 0,
      rowIndex: 0,
      dateArr: [],
      currentFirstDate: null,
      currentMonth: null,
      currentYear: null,
      todayYear: null,
      todayDate: null,
      editStatus: false,
      weekList: [
        this.$t("sunday"),
        this.$t("monday"),
        this.$t("tuesday"),
        this.$t("wednesday"),
        this.$t("thursday"),
        this.$t("friday"),
        this.$t("saturday"),
      ],
      weeksList: [
        {
          label: this.$t("sunday"),
          value: "SUNDAY",
        },
        {
          label: this.$t("monday"),
          value: "MONDAY",
        },
        {
          label: this.$t("tuesday"),
          value: "TUESDAY",
        },
        {
          label: this.$t("wednesday"),
          value: "WEDNESDAY",
        },
        {
          label: this.$t("thursday"),
          value: "THURSDAY",
        },
        {
          label: this.$t("friday"),
          value: "FRIDAY",
        },
        {
          label: this.$t("saturday"),
          value: "SATURDAY",
        },
      ],
      cycleList: [],
      classesList: [],
      _maxTime: "",
      _maxTime: "",
      pickerOptions: {
        onPick(time) {
          // 如果选择了只选择了一个时间
          if (!time.maxDate) {
            let timeRange = 3600 * 1000 * 24 * 365 * 3; // 3年
            _minTime = time.minDate.getTime() - timeRange; // 最小时间
            _maxTime = time.minDate.getTime() + timeRange; // 最大时间
            // 如果选了两个时间，那就清空本次范围判断数据，以备重选
          } else {
            _minTime = _maxTime = null;
          }
        },
      },
      loopCycle: [],
      checkTeamMemberList: [],

      checkClasses: [],
      checkCycle: [],
      postStatus: "0",
    };
  },
  created() {
    this.getData();
    this.todayYear = new Date().getFullYear();
    this.todayDate = this.formatDate(new Date(), "Y-m-d");
    let yearList = [];
    for (var i = this.todayYear - 2; i <= this.todayYear + 2; i++) {
      yearList.push({
        value: i,
        label: i,
      });
    }
    this.yearArr = yearList;
  },
  computed: {},
  watch: {
    $route: {
      handler(newValue) {
        this.editStatus = newValue.query.editStatus || 0;
      },
      immediate: true,
    },
  },
  methods: {
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.deptName,
        children: node.children,
      };
    },
    employerChange(val) {
      if (val) {
        this.queryParams.employerDeptId = null;
        deptTree(this.queryParams.employerId).then((response) => {
          this.deptOptions = response.data;
        });
      }
    },
    addDate(date, num) {
      date.setDate(date.getDate() + num);
      return date;
    },
    setDate(date) {
      const week = date.getDay();
      date = this.addDate(date, week * -1);
      this.currentFirstDate = new Date(date);
      this.currentMonth = this.currentFirstDate.getMonth();
      this.currentYear = this.currentFirstDate.getFullYear();
      let dateList = [];
      for (var i = 0; i < 7; i++) {
        dateList.push(
          this.formatDate(i == 0 ? date : this.addDate(date, 1), "Y-m-d")
        );
      }
      this.dateArr = dateList;
      this.getList();
    },
    //格式化时间
    formatDate(dateValue, format, isWeek) {
      if (typeof format === "undefined" || format === null) {
        format = "Y-m-d h:i:s";
      }
      if (dateValue == null || dateValue == "") return "";
      var d = new Date(dateValue);

      const date = {
        Y: d.getFullYear(),
        "m+": d.getMonth() + 1 < 10 ? `0${d.getMonth() + 1}` : d.getMonth() + 1,
        "d+": d.getDate() < 10 ? `0${d.getDate()}` : d.getDate(),
        "h+": d.getHours() < 10 ? `0${d.getHours()}` : d.getHours(),
        "i+": d.getMinutes() < 10 ? `0${d.getMinutes()}` : d.getMinutes(),
        "s+": d.getSeconds() < 10 ? `0${d.getSeconds()}` : d.getSeconds(),
        "q+": Math.floor((d.getMonth() + 3) / 3),
        "S+": d.getMilliseconds(),
      };

      for (let k in date) {
        if (new RegExp("(" + k + ")").test(format)) {
          format = format.replace(
            RegExp.$1,
            RegExp.$1.length === 1
              ? date[k]
              : ("00" + date[k]).substr(("" + date[k]).length)
          );
        }
      }
      if (isWeek) {
        const week = this.weekList[d.getDay()];
        format = format + week;
      }
      return format;
    },
    //上一周
    lastWeek() {
      this.setDate(this.addDate(this.currentFirstDate, -7));
    },
    //下一周
    nextWeek() {
      this.setDate(this.addDate(this.currentFirstDate, 7));
    },
    //切换月份
    selectMonth(month) {
      const date = `${this.currentYear}/${month > 9 ? month : `0${month}`}/01`;
      const weekOne = this.getFirstDayOfWeek(new Date(date));
      console.log(weekOne);
      //如果当前月第一天不是周日则往后切一周
      if (new Date(weekOne).getMonth() + 1 == month) {
        this.setDate(new Date(date));
      } else {
        this.setDate(this.addDate(new Date(date), 7));
      }
    },
    //获取当前日期所在周的周日的日期
    getFirstDayOfWeek(date) {
      var weekday = date.getDay() - 1;
      date.setDate(date.getDate() - weekday);
      return this.formatDate(date, "Y-m-d");
    },
    //切换年份
    selectYear() {
      const date = `${this.currentYear}-${this.formatDate(new Date(), "m-d")}`;
      this.setDate(new Date(date));
    },
    renderNot(h, { column, $index }) {
      let data = {};
      if (this.dataList.length) {
        data = this.dataList[0].dayList[$index - 1] || {};
      }
      return h("div", [
        h("div", column.label),
        h("div", data.statutoryHolidaysName ? data.statutoryHolidaysName : ""),
      ]);
    },
    renderHeader(h, { column, $index }) {
      let data = {};
      if (this.dataList.length) {
        data = this.dataList[0].dayList[$index - 1] || {};
      }

      return h("div", [
        h("div", [
          h("span", column.label),
          h(
            "el-tooltip",
            {
              props: {
                effect: "dark",
                content: this.$t("today"),
                placement: "top-start",
              },
            },
            [
              h("i", {
                class: "el-icon-star-off",
                style:
                  "color:#1890ff;margin-left:10px;cursor:pointer;font-size:14px;",
              }),
            ]
          ),
        ]),
        h("div", data.statutoryHolidaysName ? data.statutoryHolidaysName : ""),
      ]);
    },
    //批量操作
    batchOption() {
      this.reset();
      this.open = true;
      this.title = this.$t("batch_scheduling");
    },
    //编辑操作
    editOption(value) {
      if (value) {
        this.$router.push("/checkWork/scheduling/calendar?editStatus=1");
        this.getList();
      } else {
        this.checkClasses = [];
        this.checkCycle = [];
        this.rowIndex = 0;
        this.colIndex = 0;
        this.getList();
        this.$router.back(-1);
      }
      //this.editStatus = value;
    },
    //发布操作
    postOption() {
      this.$modal
        .confirm(this.$t("publish_current_schedule"))
        .then(() => {
          postClasses({
            startTime: this.dateArr[0],
            endTime: this.dateArr[this.dateArr.length - 1],
            empIdList: this.dataList.map((item) => item.empId),
            employerId: this.queryParams.employerId,
          }).then((res) => {
            this.getList();
            this.$modal.msgSuccess(this.$t("operation_successful"));
          });
        })
        .catch(() => {});
    },
    //保存操作
    saveOption() {
      this.dataListCopy.map((a) => {
        a.dayList.map((b) => {
          b.classesList.map((c) => {
            delete c.createTime;
            delete c.updateTime;
          });
        });
      });
      updateClasses({
        startTime: this.dateArr[0],
        endTime: this.dateArr[this.dateArr.length - 1],
        scheduleList: this.dataListCopy.map((item) => {
          return {
            ...item,
            employerId: this.queryParams.employerId,
          };
        }),
      }).then((item) => {
        this.$modal.msgSuccess(this.$t("operation_successful"));
        this.editOption(false);
      });
    },

    // 表单重置
    reset() {
      this.form = {
        id: null,
        scheduleForm: "1",
        scheduleMethod: "1",
        weeklyList: [],
        classesId: [],
        cycleId: null,
        cycleList: [],
        empIds: [],
        startTime: null,
        endTime: null,
      };
      this.loopCycle = [];
      this.checkTeamMemberList = [];
      this.resetForm("form");
    },
    //请求页面所需数据
    getData() {
      listCycleAll().then((response) => {
        this.cycleList = response.data;
      });
      listClassesAll().then((response) => {
        this.classesList = response.data;
      });
      this.setDate(new Date());
    },
    //点击选择组员按钮
    checkTeamMember() {
      this.$refs.showTips.handleAddPosition({
        employerId: this.queryParams.employerId,
      });
    },
    handleChoosePeople(e) {
      this.checkTeamMemberList = e;
    },
    handleRemoveTeamMember(index) {
      this.checkTeamMemberList.splice(index, 1);
    },
    getStartAndEndDateOfWeek(date) {
      const millisecondsOfDay = 24 * 60 * 60 * 1000;
      let dayOfWeek = date.getDay();
      if (dayOfWeek === 0) dayOfWeek = 7;
      const startDate = new Date(
        date.getTime() - (dayOfWeek - 1) * millisecondsOfDay
      );
      const endDate = new Date(
        date.getTime() + (7 - dayOfWeek) * millisecondsOfDay
      );

      return {
        startDate,
        endDate,
      };
    },

    /** 查询周期班列表 */
    getList() {
      this.loading = true;
      // let nowTime = new Date().getTime();
      getBatchList({
        ...this.queryParams,
        startTime: this.dateArr[0],
        endTime: this.dateArr[this.dateArr.length - 1],
      }).then((response) => {
        this.dataList = response.data.map((item) => {
          item.dayList = item.dayList.map((dayItem) => {
            if (dayItem.classesList == null) {
              dayItem.classesList = [];
            }
            // const dateTime = new Date(`${dayItem.date} 23:59:59`).getTime();
            // if (dateTime > nowTime) {
            //   dayItem.isEdit = true;
            // } else {
            //   dayItem.isEdit = false;
            // }
            return dayItem;
          });
          return item;
        });
        if (this.editStatus == 1) {
          this.dataList.forEach((item) => {
            let find = this.dataListCopy.find((i1) => item.empId === i1.empId);
            if (find) {
              item.dayList.map((v1, vi1) => {
                let find1 = find.dayList.find((v2) => v2.date === v1.date);
                if (find1) {
                  this.$set(item.dayList, vi1, find1);
                } else {
                  find.dayList.push(v1);
                }
              });
            } else {
              this.dataListCopy.push(item);
            }
          });
        }

        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    /** 搜索按钮操作 */
    handleQuery() {
      if (!this.queryParams.employerId) {
        this.$message.warning(
          this.$t("please_select", { name: this.$t("employer") })
        );
        return;
      }
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      // if (selection.length > 1) {
      //   let del_row = selection.shift();
      //   this.$refs.mainTable.toggleRowSelection(del_row, false); //设置这一行取消选中
      // }
      console.log(selection);
      // this.ids = selection.map((item) => item.id);
      // this.single = selection.length !== 1;
      // this.multiple = !selection.length;
    },
    //表头点击事件
    handleHeaderClick(column, event) {
      if (this.editStatus == 0) {
        return;
      }
      const $columnIndex = column.$columnIndex;
      //if ($columnIndex !== 0) this.rowIndex = 0;
      this.colIndex = $columnIndex;
      this.rowIndex = 0;
      this.checkClasses = [];
      this.checkCycle = [];
    },
    headerCellStyle({ row, column, rowIndex, columnIndex }) {
      if (this.editStatus == 0) {
        return;
      }
      if (columnIndex === 0) {
        return;
      } else if (this.colIndex === columnIndex && this.rowIndex == 0) {
        return this.setSelectStyle();
      }
    },
    handleCellClick(row, column) {
      if (this.editStatus == 0) {
        return;
      }
      const $rowIndex = row.$rowIndex;
      const $columnIndex = column.$columnIndex;
      console.log($rowIndex, $columnIndex, "fff");

      this.rowIndex = $rowIndex;
      this.colIndex = $columnIndex;
      this.checkClasses = [];
      this.checkCycle = [];
    },
    cellStyle({ row, column, rowIndex, columnIndex }) {
      if (this.editStatus == 0) {
        return;
      }
      row.$rowIndex = rowIndex + 1;
      column.$columnIndex = columnIndex;
      // 选的是列
      if (this.rowIndex === 0 && this.colIndex !== 0) {
        if (this.colIndex === columnIndex) {
          return this.setSelectStyle();
        }
      }
      // 说明是行
      else if (this.colIndex === 0) {
        if (this.rowIndex === rowIndex + 1) {
          return this.setSelectStyle();
        }
      } else {
        if (this.rowIndex === rowIndex + 1 && this.colIndex === columnIndex) {
          return this.setSelectStyle();
        }
      }
    },

    setSelectStyle() {
      return {
        background: "#e8f4dd",
        color: "#1890ff",
      };
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getCycle(id).then((response) => {
        response.data.classes =
          response.data.classes && response.data.classes.split(",");
        this.form = response.data;
        this.open = true;
        this.title = this.$t("modify");
      });
    },

    changeSchedulingForm() {
      this.form.weeklyList = [];
      this.form.classesId = [];
    },
    changeMethod() {
      this.loopCycle = [];
      this.form.startTime = null;
      this.form.endTime = null;
      this.form.classesDate = [];
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.loopCycle && this.loopCycle.length) {
            this.form.startTime = this.loopCycle[0];
            this.form.endTime = this.loopCycle[1];
          }
          if (this.checkTeamMemberList.length) {
            this.form.empIds = this.checkTeamMemberList.map((item) => item.id);
          } else {
            this.$modal.msgError(
              this.$t("please_select", { name: this.$t("employee") })
            );
            return;
          }

          if (
            this.form.scheduleMethod == 0 &&
            this.form.cycleDateList.length == 0
          ) {
            this.$modal.msgError(
              this.$t("please_select", { name: this.$t("periodic_scheduling") })
            );
            return;
          }
          // console.log(this.form);
          // return;
          this.form.employerId = this.queryParams.employerId;
          addBatchUpdate(this.form).then((response) => {
            this.$modal.msgSuccess(this.$t("operation_successful"));
            this.open = false;
            this.getList();
          });
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm(this.$t("delete_data"))
        .then(function () {
          return delCycle(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess(this.$t("operation_successful"));
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "cycle/cycle/export",
        {
          ...this.queryParams,
        },
        `cycle_${new Date().getTime()}.xlsx`
      );
    },

    classesChange(value) {
      this.checkCycle = [];
      if (value.length) {
        let classesItem = this.classesList.find((findItem) => {
          return findItem.id == value[0];
        });
        if (this.rowIndex == 0 && this.colIndex == 0) {
          this.$modal.msgError(this.$t("please_select_schedule"));
          this.checkClasses = [];
          return;
        } else {
          console.log(this.dataList, value, classesItem);
          if (this.rowIndex == 0) {
            console.log("列", this.rowIndex, this.colIndex);
            this.dataList.forEach((item) => {
              const optionItem = item.dayList[this.colIndex - 1];
              if (this.filterCondition(optionItem, classesItem)) {
                item.dayList[this.colIndex - 1].classesList.push({
                  ...classesItem,
                });
              }
            });
          } else if (this.colIndex == 0) {
            console.log("行", this.rowIndex, this.colIndex);
            const dataItem = this.dataList.find((item) => {
              return this.rowIndex == item.$rowIndex;
            });
            dataItem.dayList.forEach((item) => {
              const optionItem = item;
              if (this.filterCondition(optionItem, classesItem)) {
                item.classesList.push({
                  ...classesItem,
                });
              }
            });
            this.$set(this.dataList, this.rowIndex - 1, dataItem);
          } else {
            console.log("单格");
            const dataItem = this.dataList.find((item) => {
              return this.rowIndex == item.$rowIndex;
            });
            const optionItem = dataItem.dayList.find((item, index) => {
              return this.colIndex == index + 1;
            });

            if (this.filterCondition(optionItem, classesItem)) {
              optionItem.classesList.push({
                ...classesItem,
              });
              dataItem.dayList[this.colIndex - 1] = optionItem;
              this.$set(this.dataList, this.rowIndex - 1, dataItem);
            }
          }
        }
      }
    },
    cycleChange(value) {
      this.checkClasses = [];
      if (value.length) {
        let cycleItem = this.cycleList.find((findItem) => {
          return findItem.id == value[0];
        });
        const cycleClasses = cycleItem.shiftDTOList;
        if (cycleClasses && cycleClasses.length == 0) {
          this.$modal.msgError(this.$t("no_shifts_schedule_cycle"));
          return;
        }
        if (this.rowIndex == 0 && this.colIndex == 0) {
          this.$modal.msgError(this.$t("please_select_schedule"));
          this.checkCycle = [];
          return;
        } else {
          if (this.rowIndex == 0) {
            //选择一竖排
            console.log("选择一竖排", this.rowIndex, this.colIndex);
            const classesItem = cycleClasses[0];
            this.dataList.forEach((item) => {
              const optionItem = item.dayList[this.colIndex - 1];
              if (this.filterCondition(optionItem, classesItem)) {
                item.dayList[this.colIndex - 1].classesList.push({
                  ...classesItem,
                  cycleShiftId: cycleItem.id,
                });
              }
            });
          } else if (this.colIndex == 0) {
            //选择一横排
            console.log("选择一横排", this.rowIndex, this.colIndex);
            const dataItem = this.dataList.find((item) => {
              return this.rowIndex == item.$rowIndex;
            });
            let cycleArr = this.generateData(cycleClasses, 7);
            dataItem.dayList.forEach((item, index) => {
              const classesItemIndex = cycleArr[index];
              const classesItem = cycleClasses[classesItemIndex];
              console.log(classesItem);
              const optionItem = item;
              if (this.filterCondition(optionItem, classesItem)) {
                item.classesList.push({
                  ...classesItem,
                  cycleShiftId: cycleItem.id,
                });
              }
            });
            this.$set(this.dataList, this.rowIndex - 1, dataItem);
          } else {
            //选择单格
            const dataItem = this.dataList.find((item) => {
              return this.rowIndex == item.$rowIndex;
            });
            const optionItem = dataItem.list.find((item, index) => {
              return this.colIndex == index + 1;
            });
            const classesItem = cycleClasses[0];
            if (this.filterCondition(optionItem, classesItem)) {
              optionItem.classesList.push({
                ...classesItem,
                cycleShiftId: cycleItem.id,
              });
              dataItem.dayList[this.colIndex - 1] = optionItem;
              this.$set(this.dataList, this.rowIndex - 1, dataItem);
            }
          }
        }
      }
    },

    filterCondition(optionItem, classesItem) {
      // if (optionItem.isEdit) {
      const findIndex = optionItem.classesList.findIndex((findItem) => {
        return findItem.id == classesItem.id;
      });
      if (findIndex != -1) {
        console.log("当前排班存在，删掉");
        optionItem.classesList.splice(findIndex, 1);
      }

      if (optionItem.classesList.length == 3) {
        console.log("当天排班已排满");
        return false;
      }
      if (
        optionItem.classesList.length == 1 &&
        optionItem.classesList[0].shiftCode == "FREE"
      ) {
        console.log("原来是休息，删掉");
        optionItem.classesList.splice(0, 1);
      }
      if (optionItem.classesList.length && classesItem.shiftCode == "FREE") {
        console.log("有排班不能排休息");
        return false;
      }

      return true;
      // } else {
      //   return false;
      // }
    },

    generateData(data, days) {
      const newData = [];
      const length = data.length;
      for (let i = 0; i < days; i++) {
        newData.push(i % length);
      }
      return newData;
    },

    deleteIndexClass(row, index) {
      const optionItem = this.dataList[row.$rowIndex - 1];
      optionItem.dayList[index].classesList = [];
      this.$set(this.dataList, row.$rowIndex - 1, optionItem);
    },
  },
};
</script>
<style lang="scss" scoped>
.empty {
  min-height: 1000px;
  .tip {
    color: #909399;
  }
  ::v-deep.el-empty__description p {
    color: #333333;
    font-size: 18px;
  }
}
.month-text {
  text-align: center;
  color: #999999;
  cursor: pointer;

  &.active {
    color: #000000;
    font-weight: bold;
  }
}

.option-block {
  margin: 16px 0;

  .option-line {
    display: flex;
    align-items: flex-start;
    margin-bottom: 16px;
    font-size: 14px;

    .line-label {
      color: #000000;
      font-weight: bold;
      margin-right: 10px;
    }

    .line-value {
      flex: 1;

      .radio-class {
        margin-right: 0;
        margin-bottom: 10px;
      }
    }
  }
}

.table-cell-item {
  position: relative;

  .status-block {
    display: flex;
    align-content: flex-start;
    justify-content: space-between;

    i {
      cursor: pointer;
      color: #333333;
    }
  }

  .tag-item {
    display: inline-block;
    margin: 8px 10px;
    padding: 2px 12px;
    border-radius: 2px;
  }
}
</style>

<style>
.el-table .class-cell {
  vertical-align: top;
}
</style>
